package com.zhwmall.product.service.impl;


import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zhwmall.common.entity.product.BrandEntity;
import com.zhwmall.common.entity.product.CategoryBrandRelationEntity;
import com.zhwmall.product.dao.BrandDao;
import com.zhwmall.product.dao.CategoryBrandRelationDao;
import com.zhwmall.product.service.BrandService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service("brandService")
public class BrandServiceImpl extends ServiceImpl<BrandDao, BrandEntity> implements BrandService {

    @Autowired
    private CategoryBrandRelationDao categoryBrandRelationDao;

    @Override
    public IPage<BrandEntity> pageList(Map<String, Object> params) {
        IPage<BrandEntity> page = new Page<>(Long.parseLong((String) params.get("currentPage")), Long.parseLong((String) params.get("pageSize")));
        return baseMapper.selectPage(
                page, new QueryWrapper<BrandEntity>()
                        .like(params.get("input") != null, "name", params.get("input"))
                        .or()
                        .like(params.get("input") != null, "first_letter", params.get("input")));
    }

    @Override
    public void removeBrandByIds(List<Long> asList) {

        // TODO: 校验是否关联

        baseMapper.deleteBatchIds(asList);
    }

    @Override
    public void updateBrandAndCategoryBrandRelation(BrandEntity brand) {
        baseMapper.updateById(brand);

        CategoryBrandRelationEntity build = CategoryBrandRelationEntity.builder().brandName(brand.getName()).build();

        categoryBrandRelationDao.update(build, new QueryWrapper<CategoryBrandRelationEntity>().eq("brand_id", brand.getBrandId()));
    }

    @Override
    public List<BrandEntity> getBrandByIds(Long categoryId) {
        List<CategoryBrandRelationEntity> relations = categoryBrandRelationDao.selectList(new QueryWrapper<CategoryBrandRelationEntity>()
                .eq("catelog_id", categoryId));

        if (CollUtil.isNotEmpty(relations)){
            return relations.stream().map(item->{
                Long brandId = item.getBrandId();
                return baseMapper.selectById(brandId);
            }).collect(Collectors.toList());
        }

        return null;
    }
}